<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
    // 封装一个函数，作用和 axios 一样
    function ajax ({ method, url, params, data }){
      return new Promise((resolve, reject) => {
        let arr = []
        for (let key in params) {
        // console.log(`${key}=${params[key]}`)  // appkey=laotang   id=111
          arr.push(`${key}=${params[key]}`)
        }
        // console.log(arr) // ['appkey=laotang', 'id=111']

        const xhr = new XMLHttpRequest()

        xhr.addEventListener('load', function () {
          if (xhr.status >= 200 && xhr.status < 300) {
        // console.log('成功', JSON.parse(xhr.response))
            resolve(JSON.parse(xhr.response))
          } else if (xhr.status >= 300) {
        // console.log('失败', JSON.parse(xhr.response))
            reject(JSON.parse(xhr.response))
          }
        })

        xhr.open(method, url + '?' + arr.join('&'))

        if (typeof data === 'string') {
          // 说明提交的是查询字符串
          // console.log('提交的是查询字符串')
          xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
          xhr.send(data)
        } else if (data instanceof FormData) {
          // 说明提交的是FormData对象
          // console.log('提交FormData')
          xhr.send(data)
        } else if (data instanceof Object) {
          // 说明提交的是字面量对象
          // console.log('提交的是字面量对象')
          xhr.setRequestHeader('Content-Type', 'application/json')
          xhr.send(JSON.stringify(data))
        } else {
          xhr.send()
        }
      })
    }

    // 使用的话，和axios一样
    ajax({
      method: 'GET',
      url: 'http://www.itcbc.com:3006/api/getbooks',
      params: {
        appkey: 'heshun'
      }
    }).then(res => {
      console.log(res)
    })

    ajax({
      method: 'POST',
      url: 'http://www.itcbc.com:3006/api/addbook',
      data: {
        bookname: '西游记',
        author: '吴承恩',
        publisher: '北京出版社',
        appkey: 'heshun'
      }
    }).then(res => {
      console.log(res)
    })
    </script>
</body>
</html>